package com.yangfan.screenshot.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.ServiceConnection;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.yangfan.screenshot.event.EventCancelGesture;
import com.yangfan.screenshot.log.LogUtil;
import com.yangfan.screenshot.message.LocalMessageManager;
import com.yangfan.screenshot.message.MessageWhatConstant;
import com.yangfan.screenshot.ui.FloatButtonWindow;
import com.yangfan.screenshot.utils.ScreenUtil;

import org.greenrobot.eventbus.EventBus;

/**
 * @author : yangfan_rj
 * @date : 2022/12/6-14:47
 * desc   : 无障碍服务
 */
public class ScreenShotAccessibilityService extends AccessibilityService implements LocalMessageManager.HandleMsgListener {

    private final String TAG = ScreenShotAccessibilityService.class.getSimpleName();

    private Handler mHandler;
    private final int WHAT_SCROLL = 0x01;
    private final int startLongShot = 1;

    private int scroll_x = 0;
    private int scroll_y_start = 0;
    private int scroll_y_end = 0;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MessageWhatConstant
                    .MESSAGE_WHAT_DO_SCROLL_START:
                LogUtil.d(TAG, "MESSAGE_WHAT_DO_SCROLL_START");
                // 滑动
                doScroll();
                break;
            case MessageWhatConstant
                    .MESSAGE_WHAT_DO_SCROLL_END:
                LogUtil.d(TAG, "MESSAGE_WHAT_DO_SCROLL_END");
                LocalMessageManager.getInstance().removeMessages(MessageWhatConstant
                        .MESSAGE_WHAT_DO_SCROLL_START);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtil.d(TAG, "AccessibilityService onServiceConnected");
        LocalMessageManager.getInstance().addListener(this);

        int screenWidth = ScreenUtil.instance.getWidth();
        int screenHeight = ScreenUtil.instance.getHeight();
        scroll_x = screenWidth / 2;
        scroll_y_start = screenHeight / 4 * 3;
        scroll_y_end = screenHeight / 4 * 2;
        LogUtil.d(TAG, "scroll_y_start = " + scroll_y_start + ";scroll_y_end = " + scroll_y_end);

        HandlerThread handlerThread = new HandlerThread("AppShot");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case WHAT_SCROLL:
                        // 滚动
                        doScroll();
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        Log.d(TAG, "AccessibilityService unbindService");
        LocalMessageManager.getInstance().removeListener(this);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
    }

    @Override
    public void onInterrupt() {
        Log.d(TAG, "AccessibilityService onInterrupt");
        Toast.makeText(getApplicationContext(), "截屏服务中断，请重试", Toast.LENGTH_SHORT).show();
        LocalMessageManager.getInstance().removeListener(this);
    }

    /**
     * 做滚动
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void doScroll() {
        LogUtil.d(TAG, "doScroll...");
        Path path = new Path();
        path.moveTo(scroll_x, scroll_y_start);
        path.lineTo(scroll_x, scroll_y_end);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 0, 1000))
                .build();

        dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.d(TAG, "GestureDescription onCompleted");
                // 滑动完后，通知截屏
                LocalMessageManager.getInstance().sendEmptyMessage(MessageWhatConstant.MESSAGE_WHAT_CAPTURE);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);

                mHandler.removeMessages(WHAT_SCROLL);
                int currentNum = FloatButtonWindow.Companion.getCancelNumber() + 1;
                FloatButtonWindow.Companion.setCancelNumber(currentNum);
                Log.d(TAG, "GestureDescription onCancelled " + currentNum);
                // 发现会先走两次onCanceled 第三次就是人为的了 这里有时候是第2次有时候第3次，原因不明
                if (currentNum >= 2) {
                    EventBus.getDefault().post(new EventCancelGesture());
                }

            }

        }, mHandler);
    }

}
